# -*- coding: utf-8 -*-
# @Time    : 2019/2/25 14:11
# @Author  : yueconger
# @File    : DB_Comparison.py
# 更新法律法规与库中数据对比
import os
import re
from chinacourt_law.mysql_db import ConnDB


class DBComparison(object):
    """
    更新法律法规与库中数据对比
    """

    def __init__(self):
        self.pool = ConnDB().conPool
        self.conn = self.pool.connection()
        self.db_cursor = self.conn.cursor()

    def law_chinacourt_name(self):
        file_path = r'E:\LocalServer\chinacourt\html_new/'
        html_list = os.listdir(file_path)  # 列出文件夹下所有的目录与文件
        count = 0
        for i in range(0, len(html_list)):
            html_path = os.path.join(file_path, html_list[i])
            law_chinacourt = html_path.split('/')[-1].split('.')[0]
            print('当前法规', law_chinacourt)
            # 第一次过滤, 将法律名完全一致的去除
            result = self.complate_law(law_chinacourt)
            if isinstance(result, tuple):
                print('原数据库中已存在!')
                pass
            else:
                law_chinacourt_new = re.sub('（.*?）', '', law_chinacourt)
                result_similar = self.similar_law(law_chinacourt_new)
                if isinstance(result_similar, tuple):
                    print('此时:', result_similar)
                else:
                    self.write2txt_name(law_chinacourt)
                    print('可能新增', law_chinacourt)

            print('--------------')

    def complate_law(self, law_name):
        """
        对比名称完全匹配法律法规
        :return:
        """
        sql = """select law_name, issue_date from kb_mainlaw WHERE law_name = '%s'""" % (law_name)
        print(sql)
        try:
            res_db = self.db_cursor.execute(sql)
        except:
            print('查询有误!')
            return ['没有']
        if res_db > 0:
            results = self.db_cursor.fetchall()
            return results
        else:
            return ['无']

    def similar_law(self, law_name):
        """
        对比名称模糊匹配法律法规
        :return:
        """
        sql = """select law_name, issue_date from kb_mainlaw WHERE law_name LIKE '%s'""" % ('%'+ law_name.strip() + '%')
        print(sql)
        try:
            res_db = self.db_cursor.execute(sql)
        except:
            print('查询有误!')
            return ['没有']
        if res_db > 0:
            results = self.db_cursor.fetchall()
            return results
        else:
            return ['无']

    def write2txt_name(self, law_name):
        txt_path = r'E:\LocalServer\chinacourt\law_name_chinacourt_up.txt'
        with open(txt_path, 'a+', encoding='utf-8') as f:
            f.write(law_name+'\n')


if __name__ == '__main__':
    db_com = DBComparison()

    db_com.law_chinacourt_name()
